package project.rbac.service.impl;

import project.rbac.dao.IUserDao;
import project.rbac.dao.collection.UserDao;
import project.rbac.domain.dto.UserDto;
import project.rbac.domain.entity.Dept;
import project.rbac.domain.entity.Role;
import project.rbac.domain.entity.User;
import project.rbac.domain.vo.Result;
import project.rbac.domain.vo.UserVo;
import project.rbac.service.IDeptService;
import project.rbac.service.IRoleService;
import project.rbac.service.IUserService;
import project.rbac.util.SingletonFactory;
import project.rbac.view.MainView;

import java.time.LocalDateTime;
import java.util.Collection;


/**
 * 业务层-用户
 *
 * @author 刘嘉薏
 * @since 2025/5/16 10:30
 */
public class UserService extends BaseService<User, UserDto, UserVo, IUserDao> implements IUserService {

    private final IDeptService deptService;
    private final IRoleService roleService;
    private UserService() {
        deptService = SingletonFactory.getInstance(DeptService.class);
        roleService = SingletonFactory.getInstance(RoleService.class);
        dao = SingletonFactory.getInstance(UserDao.class);
        temp = new UserVo[0];
    }
    @Override
    UserVo convertToVo(User user) {
        String deptName = "";
        Dept dept = deptService.findById(user.deptId);
        if (dept != null) {
            deptName = dept.name;
        }
        String roleName = "";
        Role role = roleService.findById(user.roleId);
        if (role != null) {
            roleName = role.name;
        }
        return new UserVo(user.getId(), user.createAt, user.updateAt,user.username, user.name, user.mobile,
                user.email, user.deptId, deptName, user.roleId, roleName, user.enabled);
    }

    @Override
    User createEntity(UserDto dto) {
        LocalDateTime now = LocalDateTime.now();
        return new User(null,now, now,dto.username, dto.name, dto.mobile, dto.email, dto.deptId,
                dto.roleId,dto.password);
    }

    @Override
    void updateEntity(UserDto dto, User user) {
        user.updateAt = LocalDateTime.now();
        user.username = dto.username;
        user.name = dto.name;
        user.mobile = dto.mobile;
        user.email = dto.email;
        user.deptId = dto.deptId;
        user.roleId = dto.roleId;
    }
    @Override
    public  boolean deptInUse(int deptId){
        boolean inUse = false;
        Collection<User> values = dao.list();
        for (User user : values){
            if (user!=null && user.deptId == deptId){
                inUse = true;
                break;
            }
        }
        return inUse;
    }
    @Override
    public  boolean roleInUse(int roleId){
        boolean inUse = false;
        Collection<User> values = dao.list();
        for (User user : values){
            if (user!=null && user.roleId == roleId){
                inUse = true;
                break;
            }
        }
        return inUse;
    }

    @Override
    public  Result create(UserDto dto) {
        if (!deptService.existsById(dto.deptId)) {
            return Result.failure("创建失败，不存在指定的部门");
        }
        if (!roleService.existsById(dto.roleId)) {
            return Result.failure("创建失败，不存在指定的角色");
        }
        return super.create(dto);
    }
    @Override
    public boolean verifyPassword(int userId, String inputPassword) {
        User user = dao.findById(userId);
        if (user == null) {
            System.out.println("用户不存在，ID: " + userId);
            return false;
        }
        if (!user.password.equals(inputPassword)) {
            System.out.println("旧密码不匹配，输入的密码: " + inputPassword + ", 数据库中的密码: " + user.password);
            return false;
        }
        return true;
    }

    @Override
    public  Result update(UserDto dto, int id) {
        System.out.print("请输入当前密码验证身份：");
        String currentPassword = MainView.input.nextLine();
        if (!verifyPassword(id, currentPassword)) {
            return Result.failure("密码验证失败");
        }
        if (!deptService.existsById(dto.deptId)) {
            return Result.failure("更新失败，不存在指定的部门");
        }
        if (!roleService.existsById(dto.roleId)) {
            return Result.failure("更新失败，不存在指定的角色");
        }
        return  super.update(dto, id);
    }
    @Override
    public  Result toggle(int id){
        if (!existsById(id)) {
            return Result.failure("切换状态失败，不存在该数据");
        }
        User user = dao.findById(id);
        user.enabled = !user.enabled;
        user = dao.save(user);
        return Result.success(user.enabled ?  "启用成功" : "停用成功", null);
    }

    @Override
    public Result changePassword(Integer id, String oldPassword, String newPassword) {
        User user = findById(id);
        if (user == null || !user.password.equals(oldPassword)) {
            return Result.failure("旧密码错误");
        }
        user.password = newPassword;
        return Result.success("密码修改成功", null);
    }
}
